import streamlit as st
from multi_download import multi_download
import os
import requests
import datetime
# 爬取我的世界版本列表
def get_minecraft_java_releases():
    url = "https://launchermeta.mojang.com/mc/game/version_manifest.json"
    response = requests.get(url)
    response.raise_for_status()  # 确保请求成功
    version_manifest = response.json()

    releases = []
    for version_info in version_manifest["versions"]:
        if version_info["type"] == "release":  # 只筛选正式版
            version_id = version_info["id"]
            releases.append(version_id)
    
    return releases
def check_version(version,target_version):
    # 将版本号字符串分割成列表，例如 "1.12" -> [1, 12]
    version_parts = list(map(int, version.split('.')))
    
    # 比较版本号
    if version_parts < target_version:
        return True
# 获取Github上的最新Release并使用镜像站下载
def git_download(repo_owner, repo_name):
    """
    获取GitHub项目最新稳定版本的下载链接
    :param repo_owner: 项目所有者用户名
    :param repo_name: 项目名称
    """
    url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
    response = requests.get(url)
    if response.status_code == 200:
        release_info = response.json()
        # 遍历assets获取下载链接
        for asset in release_info.get('assets', []):
            multi_download(asset['browser_download_url'],"./{folder_name}/plugins/")
    else:
        st.error(f"获取最新版本失败，状态码：{response.status_code}")
# 开始打包服务端
def pack_server(serv_name, version):
    now = datetime.now()
    folder_name = now.strftime('%Y%m%d_%H%M%S')
    os.mkdir(folder_name)
    if serv_name == "Paper":
        if check_version(version, [1, 8, 8]):
            pbar.progress(20,text="正在下载服务端...")
            multi_download(f"https://tlcdn-sync.mcsl.com.cn/core/{serv_name}/{version}/lastest/download",f"./{folder_name}")
            os.mkdir(f"./{folder_name}/plugins")
            with open("./{folder_name}/start.bat","w+") as f:
                f.write(f"java -jar -Xmx{run_memory}M server.jar nogui")
            pbar.progress(40,text="正在安装插件/配置服务器...")
        else:
            st.error("该版本不支持Paper服务端！")
    for plugin in plugin_select:
            if "Essentials" in plugin:
                multi_download()
            if "LuckPerms" in plugin:
                multi_download()
            if "Vault" in plugin:
                multi_download()
            if "AuthMe" in plugin:
                multi_download()
            if "MOTD" in plugin:
                multi_download()
            if "ViaVersion" in plugin:
                multi_download()
            if "PlugmanX" in plugin:
                multi_download()
            if "Geyser" in plugin:
                multi_download()
            if "CoreProtect" in plugin:
                multi_download()
# 开头欢迎
st.title("快速创建Minecraft服务端")
st.write("使您能够快速创建一个带有基本Minecraft插件的Minecraft服务端。")
st.info("由 Code_S96 用 ❤ 制作")
st.warning("注意：本项目仅供学习交流使用，请勿用于商业用途！\n服务器核心来自MCSL-Sync核心镜像站。")
# 一条分割线
st.divider()
# 设定面板
st.markdown("## 基础设置")
serv_name = st.selectbox("选择你的服务端：", ["Paper", "Purpur","Spigot"])
serv_ver = st.selectbox("选择你的服务端版本：",get_minecraft_java_releases())
dificulty = st.selectbox("选择你的服务端难度：",['简单','普通','困难'])
live_mode = st.selectbox("选择你的服务端游戏模式：",['生存','创造','冒险'])
serv_port = st.number_input("请输入你的服务端端口：", value=25565, min_value=10000, max_value=65535, step=1)
run_memory = st.number_input("请输入你的服务端最大运行内存：", min_value=100,step=1)

hardcore = st.checkbox("是否开启极限模式？")
online_mode = st.checkbox("是否开启正版模式？")
allow_flight = st.checkbox("是否允许玩家飞行？")
st.divider()
st.markdown("## 插件设置")
st.write("选择你要安装的插件：")
plugin_list = ["基本命令（Essentials）","权限管理（LuckPerms）","经济插件（Vault）","登录插件（AuthMe）","高级MOTD（MOTD）","前后版本支持（ViaVersion）","插件热加载（PlugmanX）","基岩版支持（Geyser）","防熊回滚插件（CoreProtect）"]
plugin_select = st.multiselect("选择插件：", placeholder="请选择插件...", options=plugin_list)
st.divider()
pbar = st.progress(0,text="已准备就绪。")